import axios from 'axios'
import { showToast, showFailToast } from 'vant'
import router from '@/router'

const service = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL || '/api',
  timeout: 10000
})

service.interceptors.request.use(
  config => {
    const token = localStorage.getItem('token')
    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

service.interceptors.response.use(
  response => {
    const res = response.data
    
    if (res.code !== 200) {
      showFailToast(res.message || 'Error')
      
      if (res.code === 401 || res.code === 403) {
        router.push('/login')
      }
      
      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      return res
    }
  },
  error => {
    let message = error.message
    if (error.response) {
      switch (error.response.status) {
        case 400: message = '请求错误'; break
        case 401: 
          message = '未授权，请登录'
          router.push('/login')
          break
        case 403: message = '拒绝访问'; break
        case 404: message = `请求地址出错: ${error.response.config.url}`; break
        case 500: message = '服务器内部错误'; break
        default: message = '网络错误'
      }
    }
    showFailToast(message)
    return Promise.reject(error)
  }
)

export default service